package com.bite.lesson1;

import java.io.IOException;
import java.net.BindException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;
import java.nio.charset.StandardCharsets;

public class UdpEchoServer {
    //声明服务器对象
    private DatagramSocket socket = null;

    //构造方法指定端口号
    public UdpEchoServer(int port) throws SocketException {
        if (port < 1024 || port > 65535) {
            throw new BindException("端口号错误......");
        }
        //初始化UDP对象
        socket = new DatagramSocket(port);
    }

    //处理用户
    public void start() throws IOException {
        System.out.println("服务器已启动......");
        //一直循环，保持服务器持续运行
        while (true) {
            //使用DatagramPacket来接受客户端传来的数据
            DatagramPacket requestPacket = new DatagramPacket(new byte[1024],1024);
            //服务器接受数据
            socket.receive(requestPacket);
            //接受并解析数据
            String request = new String(requestPacket.getData(),0,requestPacket.getLength(),"UTF-8");


            // 通过请求计算响应
            String reponse = process(request);
            ////使用DatagramPacket来接受响应
            DatagramPacket responsePacket = new DatagramPacket(reponse.getBytes(StandardCharsets.UTF_8),0,reponse.getBytes().length,requestPacket.getSocketAddress());
            //发送响应
            socket.send(responsePacket);
            //打印日志
            System.out.printf("[%s : %d] request = %s, response = %s\n",requestPacket.getAddress().toString(),requestPacket.getPort(),request,reponse);
        }
    }

    public String process(String request) {
        return request;
    }

    public static void main(String[] args) throws IOException {
        UdpEchoServer server = new UdpEchoServer(8888);
        server.start();
    }
}
